package com.immer.session;

import com.immer.session.request.RedisClusterRequestWrapper;
import com.immer.session.request.RequestEventSubject;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  session 集群管理类
 *  @Author
 */
public class SessionClusterFilter implements Filter {

    private static final String[] STATIC_RESOURCE_PREFIX = {".png", ".jpg", ".jpeg", ".gif", ".css", ".js", ".html", ".htm",".ico"};

    private RedisSessionManger sessionCacheManger;

    public SessionClusterFilter(RedisSessionManger sessionCacheManger) {
        this.sessionCacheManger = sessionCacheManger;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            if (isIgnoreRequest(request)){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            RequestEventSubject requestEventSubject = new RequestEventSubject();
            try {
                RedisClusterRequestWrapper requestWrapper = new RedisClusterRequestWrapper(request, response);
                requestWrapper.setEventObserver(requestEventSubject);
                requestWrapper.setSessionCacheManger(sessionCacheManger);
                filterChain.doFilter(requestWrapper, servletResponse);
            } finally {
                requestEventSubject.completedRequest(request, response);
            }
        }
    }

    private static boolean isIgnoreRequest(HttpServletRequest request) {
        String url = request.getRequestURI().toLowerCase();
        for (String prefix : STATIC_RESOURCE_PREFIX) {
            if (url.endsWith(prefix)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}
